<?php

function stock_info_stats_page()
{
    global $base_url;

    drupal_add_js('sites/all/libraries/echarts/echarts-all.js', array('type' => 'file'));
    drupal_add_js('sites/all/libraries/echarts/geoJson/china-main-city-map.js', array('type' => 'file'));
    drupal_add_js("var nonghuaBaseUrl = '$base_url';", array('type' => 'inline', 'scope' => 'footer'));
    drupal_add_js('sites/all/libraries/echarts/map.js', array('type' => 'file', 'scope' => 'footer'));
    drupal_add_js(drupal_get_path('module', 'stock_info') . '/js/stock_info.js', array('type' => 'file', 'scope' => 'footer'));
    drupal_add_js ( drupal_get_path ( 'module', 'nonghua_common' ) . '/jquery.url.js' );
    drupal_add_js ( drupal_get_path ( 'module', 'nonghua_common' ) . '/ajax.js' );

//    @$output = add_toggle_button();
//    $output .= add_map();
//    $output .= add_charts();
//    $output .= "<input id='stockinfoStat' type='button' onclick='getDistributorStockInfoStat()' value='库存统计信息' class='btn btn-mini'>";
   @ $output = drupal_render(drupal_get_form('stock_info_stats_form'));

    return $output;
}

function stock_info_stats_form($form, &$form_state)
{
    $form['national_id'] = array('#type' => 'hidden', '#default_value' => '');
    $form['geo_level'] = array('#type' => 'hidden', '#default_value' => '');
    $form['geo_name'] = array('#type' => 'hidden', '#default_value' => '');
    $form['map_or_zone'] = array('#type' => 'hidden', '#default_value' => 'map');
    $form['toggle-button']['#markup'] = add_toggle_button();
    $form['map']['#markup'] = add_map();
    $form['charts']['#markup'] = add_charts();

    $form['zone']['btn']['#markup']="<input id='stockinfoStat' type='button' onclick='getDistributorStockInfoStat()' value='库存统计信息' class='btn btn-mini'>";
    $form['zone']['wrapper-zone']['#markup']='<div id="zone-wrapper-div">';
    $form['zone']['inner'] = _insert_salesman_distributor_selection_form($form, $form_state, 'zone', 'inner');
    $form['zone']['wrapper-zone-close']['#markup']="</div><input id='jurisStockStat' type='button' onclick='getjurisStockStats()'value='区域销售统计信息' class='btn btn-mini'>";
  
    $year_options['']='--年份--';
    for ($i = 0; $i < 5; $i++) {
        $year_options[date('Y')-$i] = date('Y')-$i;
    }
    $form['search']['wrapper']['#markup']='<div id="search-wrapper-div" style="clear:both;">';
//    $form['help']['#markup'] = _is_mobile()?"":'<div id="help"><a href="'.base_path().'" data-toggle="modal" target = "_blank">
//                                        <img src="'.base_path().'sites/all/themes/tweme/images/help.png"/>
//                                 </a></div>';
    $form['stats']['year'] = array(
        '#type' => 'select',
        '#validated' => TRUE,
        '#required' => TRUE,
        '#options' => $year_options,
        '#default_value' => date('Y'),
    );

    $month_options['']='--月份--';
    for ($i = 1; $i < 13; $i++) {
        $month_options[$i] = $i;
    }
    $form['stats']['month'] = array(
        '#type' => 'select',
        '#validated' => TRUE,
        '#required' => TRUE,
        '#options' => $month_options,
        '#default_value' => date('n'),
    );
    $form['stats']['search'] = array(
        '#type' => 'button',
        '#value' => t('查询'),
        '#ajax' => array(
            'callback' => 'search_callback',
            'wrapper' => 'search-wrapper-div',
            'method' => 'replace',
            'effect' => 'fade',

        ),
        '#validate' => array('check_year_not_empty', 'check_month_not_empty', 'check_geo_name_not_empty','check_zone_not_empty'),
    );
    $form['search']['table']['#markup'] = data_list_view_page($form_state);
    $form['search']['wrapper-close']['#markup']='</div>';
//    $table['#markup'] = data_list_view_page( $form_state);
//    ajax_submit_form($form, $form_state, $table, '', array('check_year_not_empty', 'check_month_not_empty', 'check_geo_name_not_empty', 'check_zone_not_empty'));
//    $form['wrapper-close']['#markup']='</div>';
    return $form;
}

function add_map()
{
    $output = '<div id="map-wrapper-div" class="clearfix">
                    <div id="divMap" class="divMapSize" ></div>
                    <input type="button" id="map_previous" value="上一级" class="btn btn-mini">
                    <input type="button" id="map_next" value="下一级" class="btn btn-mini">
               </div>';

    return $output;
}

function add_toggle_button()
{
    $output = '<div class="btn-group btn-radio" data-toggle="buttons-radio">
             <button data-toggle="button" id="map" class="btn btn-small">地图</button>
             <button data-toggle="button" id="zone" class="btn btn-small">区域</button>
           </div>';
    return $output;
}

function add_charts()
{
    // $output = '<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    //                 <div class="modal-header">
    //                     <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    //                     <h3 id="myModalLabel">库存统计信息 （同比、环比）</h3>
    //                   </div>
    //                 <div id="divYoY_thisMonthStock" class="divLineChartSize" ></div>
    //                 <div id="divQoQ_thisMonthStock" class="divLineChartSize" ></div>
    //             </div>';
      
      $output = '<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
               <div class="modal-dialog">
                  <div class="modal-content">
                     <div class="modal-header">
                        <button type="button" class="close" 
                           data-dismiss="modal" aria-hidden="true">
                              &times;
                        </button>
                        <h3 id="myModalLabel">库存统计信息 （同比、环比）</h3>
                     </div>
                    <div id="divYoY_thisMonthStock" class="divLineChartSize" ></div>
                    <div id="divQoQ_thisMonthStock" class="divLineChartSize" ></div>
                  </div>
                </div>
            </div>';

    return $output;
}

/**
 * Implements hook_validate().
 */
function stock_info_stats_form_validate($form, &$form_state)
{

}

function stock_info_stats_form_submit($form, &$form_state)
{

}

function check_year_not_empty($form, &$form_state)
{
    if ($form_state['values']['map_or_zone'] == 'map' && empty($form_state['values']['year'])) {
        form_set_error('year', '年 不能为空');
    }
}

function check_month_not_empty($form, &$form_state)
{
    if ($form_state['values']['map_or_zone'] == 'map' && empty($form_state['values']['month'])) {
        form_set_error('month', '月 不能为空');
    }
}

function check_geo_name_not_empty($form, &$form_state)
{
    if ($form_state['values']['map_or_zone'] == 'map' && empty($form_state['values']['geo_name'])) {
        form_set_error('', '未选中地理区域');
    }
}

function check_zone_not_empty($form, &$form_state)
{
    if ($form_state['values']['map_or_zone'] == 'zone' && empty($form_state['values']['juris'])) {
        form_set_error('juris', '未选中区域');
    }
}

function salesman_change_callback($form, &$form_state)
{
    return $form['zone']['juris'];
}

function data_list_view_page($form_state)
{
    $output = '';
//    $res_img = _is_mobile()?"":"<img src='".base_path()."sites/all/themes/tweme/images/result.png'>";
//    $output .="<div class='table-div'>$res_img<div class='table-border-div'>";
    //表头
    $header = array(
        array('data' => '经销商', 'class' => ['essential distributor']),
        array('data' => '撒可富化肥品种', 'class' => ['essential sacfvariety']),
        array('data' => '配比', 'class' => 'optional proportion'),
        array('data' => 'SM', 'class' => 'optional SM'),
        array('data' => '年份', 'class' => ['integrant optional year'], 'field' => 'year'),
        array('data' => '月份', 'class' => ['optional month']),
        array('data' => '上月库存量', 'class' => ['essential break last_month_stock']),
        array('data' => '回库量', 'class' => ['essential break return_stock']),
        array('data' => '当月进库量', 'class' => ['essential break this_month_instock']),
        array('data' => '当月出库量', 'class' => ['essential break this_month_outstock']),
        array('data' => '当月库量', 'class' => ['essential break this_month_stock']),
        array('data' => '当月销量', 'class' => ['essential break this_month_sales']),
        array('data' => '库存变化', 'class' => ['essential more']),
    );
    $rows = array();

    // if ($form_state['triggering_element']['#value'] == '查询') {
        $geo_level = $form_state['values']['geo_level'];
        if ($geo_level == '1') {
            $join_column = 'province_id';
        } else if ($geo_level == '2') {
            $join_column = 'city_id';
        } else if ($geo_level == '3') {
            $join_column = 'county_id';
        } else if ($geo_level == '4') {
            $join_column = 'town_id';
        } else {
            $join_column = 'village_id';
        }
        $map_or_zone = $form_state['values']['map_or_zone'];
        $juris = $form_state['values']['juris'];
        $salesman = $form_state['values']['salesman'];
        $distributor = $form_state['values']['distributor'];

        $sub_query = db_select('years', 'Y');
        $sub_query->join('months', 'M');
        $sub_query->condition('Y.year', $form_state['values']['year']);
        $sub_query->condition('M.month', $form_state['values']['month']);
        $sub_query->addField('Y', 'year');
        $sub_query->addField('M', 'month');

        $query = db_select('distributor', 'D')->extend('PagerDefault')->extend('TableSort');

        if ($map_or_zone == 'map') {
            $query->join('addr', 'A1', 'A1.addr_id=D.addr_id');
            if ($geo_level <= 2) {
                $query->join('addr', 'A2', "A2.addr_id=A1.$join_column");
            } else {
                $query->join('addr', 'A2', "A2.addr_id=A1.$join_column");
                $query->join('addr', 'A3', "A3.addr_id=A2.pid");
            }
        } else {
            if (!empty($distributor)) {
                // join nothing
            } else if (!empty($salesman)) {
                $query->join('salesman_distributor_map', 'SD', 'SD.distributor_id = D.distributor_id');
            } else if (!empty($juris)) {
                $query->join('salesman_distributor_map', 'SD', 'SD.distributor_id = D.distributor_id');
                $query->join('employee', 'E', 'E.employee_id = SD.salesman_id');
            }
        }
        $query->join($sub_query, 'T');
        $query->leftJoin('stock_info', 'S', 'S.year=T.year and S.month=T.month and S.distributor_id=D.distributor_id');
        $query->leftJoin('product_sku', 'V', 'V.product_sku_id=S.sacfvariety_id');

        if ($map_or_zone == 'map') {
            if ($geo_level <= 2) {
                $query->condition('A2.national_id', $form_state['values']['national_id']);
            } else {
                $query->condition('A3.national_id', $form_state['values']['national_id']);
                $query->condition('A2.name', $form_state['values']['geo_name']);
            }
        } else {
            if (!empty($distributor)) {
                $query->condition('D.distributor_id', $distributor);
            } else if (!empty($salesman)) {
                $query->condition('SD.salesman_id', $salesman);
            } else if (!empty($juris)) {
                $query->condition('E.juris_id', $juris);
            }
        }

        $query->addField('D', 'distributor_id');
        $query->addField('D', 'distributor_name');
        $query->addField('T', 'year');
        $query->addField('T', 'month');
        $query->addField('V', 'product_sku_id');
        $query->addField('V', 'variety_name');
        $query->addField('V', 'proportion');
        $query->addField('V', 'SM');
        $query->addField('S', 'sacfvariety_id');
        $query->addField('S', 'last_month_stock');
        $query->addField('S', 'return_stock');
        $query->addField('S', 'this_month_instock');
        $query->addField('S', 'this_month_outstock');
        $query->addField('S', 'this_month_stock');
        $query->addField('S', 'this_month_sales');
        if($form_state['triggering_element']['#value'] != '查询')
            $query->orderBy('S.timestamp', 'DESC');
        $query->limit(variable_get("list_page_item_number", 10));

        $stock_infoInfo = $query->orderByHeader($header)->execute();

        foreach ($stock_infoInfo as $row) {
            if(!empty($row->variety_name)){
                $button = '<input type="button"  data-toggle="modal" data-target="#myModal" class="btn btn-mini" value="查看" ';
            }else{
                $button = '<input type="button"  data-toggle="modal" data-target="#myModal" disabled="true" class="btn btn-mini" value="查看" ';
            }
            $rows[] = array(
                array('data' => '<a href="'.base_path().'distributor/edit/' . $row->distributor_id . '" data-toggle="modal" target = "_blank">'.$row->distributor_name.'</a>', 'class' => ['integrant essential distributor_name']),
                array('data' => $row->variety_name, 'class' => ['essential sacfvariety']),
                array('data' => $row->proportion, 'class' => 'optional proportion'),
                array('data' => $row->SM, 'class' => 'optional SM'),
                array('data' => $row->year, 'class' => ['optional year']),
                array('data' => $row->month, 'class' => ['optional year']),
                array('data' => $row->last_month_stock, 'class' => ['integrant essential break last_month_stock']),
                array('data' => $row->return_stock, 'class' => ['essential break return_stock']),
                array('data' => $row->this_month_instock, 'class' => ['essential break this_month_instock']),
                array('data' => $row->this_month_outstock, 'class' => ['essential break this_month_outstock']),
                array('data' => $row->this_month_stock, 'class' => ['essential break this_month_stock']),
                array('data' => $row->this_month_sales, 'class' => ['essential break this_month_sales']),
                array('data' =>$button. 'onclick="getDistributorStockInfoStats(' . "$row->distributor_id,$row->year,$row->month,$row->product_sku_id" . ')"/>', 'class' => 'integrant essential delete'),
            );
        }
    // }

    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格

    $output .= theme('pager');
//    $output .='</div></div>';
    return $output;
}

function search_callback($form, &$form_state)
{
    return $form['search'];
}